package model;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

public class Product extends ComponentCommon {
	
	public static Product create(String name){
		return new Product(name, new HashMap<Component, Integer>());
	}
	
	private Map<Component, Integer> subProducts;

	private Product(String name, Map<Component, Integer> subProducts) {
		super(name);
		this.subProducts = subProducts;
	}

	public Map<Component, Integer> getSubProducts() {
		return subProducts;
	}
	
	public void addSubProducts (Component subProduct, Integer amount) {
		if (this.getSubProducts().containsKey(subProduct)){
			this.getSubProducts().put(subProduct, this.getSubProducts().get(subProduct) + amount);
		} else {
			if (subProduct.contains(this))
				throw new Error("Cycle detected!");
			this.getSubProducts().put(subProduct, amount);
		}
	}

	@Override
	public boolean contains(Component argument) {
		if (argument.equals(this))
			return true;
		Iterator<Component> mySubProducts = this.getSubProducts().keySet().iterator();
		while (mySubProducts.hasNext()){
			Component current = mySubProducts.next();
			if (current.contains(argument))
				return true;
		}
		return false;
	}
}
